package com.peas.platform.module.icims.contract.initial.domain.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.peas.platform.framework.mybatisplus.domain.BaseDomainImpl;
import com.peas.platform.framework.mybatisplus.repository.BaseRepository;
import com.peas.platform.module.icims.base.sys.service.SequenceService;
import com.peas.platform.module.icims.contract.initial.adapter.repository.ContractInitialRepository;
import com.peas.platform.module.icims.contract.initial.adapter.repository.po.ContractInitialPo;
import com.peas.platform.module.icims.contract.initial.domain.ContractInitialDomain;
import com.peas.platform.module.icims.contract.initial.dto.ContractInitialDto;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

@Component
public class ContractInitialDomainImpl extends BaseDomainImpl<ContractInitialDto, ContractInitialPo> implements ContractInitialDomain {

    @Resource
    private ContractInitialRepository contractInitialRepository;
    @Resource
    private SequenceService sequenceService;

    @Override
    public BaseRepository<ContractInitialPo> getMapper() {
        return contractInitialRepository;
    }

    @Override
    public Class<? extends BaseRepository<ContractInitialPo>> getRepositoryClass() {
        return ContractInitialRepository.class;
    }

    @Transactional
    @Override
    public int save(ContractInitialDto dto) {
        if (StrUtil.isBlank(dto.getCode())) {
            String code = sequenceService.genSequence("contract", "ContractInitialDto", "CID", 4, 1);
            dto.setCode(code);
        }
        int result = super.save(dto);
        this.checkRepetition("code", dto.getCode());
        return result;
    }

    @Transactional
    @Override
    public int updateById(ContractInitialDto dto) {
        int result = super.updateById(dto);
        this.checkRepetition("code", dto.getCode());
        return result;
    }

    @Override
    public long count(String field, List<? extends Serializable> values, ContractInitialDto condition) {
        Map<String, Object> map = BeanUtil.beanToMap(condition);
        if (StrUtil.isNotBlank(field) && CollUtil.isNotEmpty(values)) {
            map.put(field, values);
        }
        QueryWrapper<ContractInitialPo> wrapper = super.buildWrapper(map);
        return this.getMapper().selectCount(wrapper);
    }

}
